package snowflake;

/**
 * Snowflake算法是带有时间戳的全局唯一ID生成算法。它有一套固定的ID格式，如下：
 *41位的时间序列（精确到毫秒，41位的长度可以使用69年）
 * 10位的机器标识（10位的长度最多支持部署1024个节点）
 *优点是：整体上按照时间自增排序，且整个分布式系统内不会产生ID碰撞(由数据中心ID和机器ID作区分)
 * @author dycong
 * @date 2018/5/3 13:16
 */
public class IdWorker {
    private final long workerId;
    /*开始时间截*/
    private final static long twepoch = 1288834974657L;
    private long sequence = 0L;
    /* 机器ID所占位数*/
    private final static long workerIdBits = 10L;
    /*机器ID最大值1023 (此移位算法可很快计算出n位二进制数所能表示的最大十进制数)*/
    public final static long maxWorkerId = -1L ^ -1L << workerIdBits;
    /*Sequence所占位数*/
    private final static long sequenceBits = 12L;
    /*机器ID偏移量*/
    private final static long workerIdShift = sequenceBits;
    /*时间戳的偏移量*/
    private final static long timestampLeftShift = sequenceBits + workerIdBits;
    /*Sequence掩码1024*/
    public final static long sequenceMask = -1L ^ -1L << sequenceBits;

    private long lastTimestamp = -1L;

    public IdWorker(final long workerId) {
        super();
        if (workerId > this.maxWorkerId || workerId < 0) {
            throw new IllegalArgumentException(String.format(
                    "worker Id can't be greater than %d or less than 0",
                    this.maxWorkerId));
        }
        this.workerId = workerId;
    }

    public synchronized long nextId() {
        long timestamp = this.timeGen();
        if (this.lastTimestamp == timestamp) {
            this.sequence = (this.sequence + 1) & this.sequenceMask;
            /*本毫秒产生序列到最大值：1024；阻塞到下一毫秒,获得新时间戳*/
            if (this.sequence == 0) {
                System.out.println("###########" + sequenceMask);
                timestamp = this.tilNextMillis(this.lastTimestamp);
            }
        } else {
            /*时间戳改变，毫秒内sequence重置*/
            this.sequence = 0;
        }
        if (timestamp < this.lastTimestamp) {
            try {
                /*时钟回退*/
                throw new Exception(
                        String.format(
                                "Clock moved backwards.  Refusing to generate id for %d milliseconds",
                                this.lastTimestamp - timestamp));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        this.lastTimestamp = timestamp;
        /*移位并通过或运算组成64位ID*/
        long nextId = ((timestamp - twepoch << timestampLeftShift))
                | (this.workerId << this.workerIdShift) | (this.sequence);
        System.out.println("timestamp:" + timestamp + ",timestampLeftShift:"
                + timestampLeftShift + ",nextId:" + nextId + ",workerId:"
                + workerId + ",sequence:" + sequence);
        return nextId;
    }

    private long tilNextMillis(final long lastTimestamp) {
        long timestamp = this.timeGen();
        while (timestamp <= lastTimestamp) {
            timestamp = this.timeGen();
        }
        return timestamp;
    }

    private long timeGen() {
        return System.currentTimeMillis();
    }


    public static void main(String[] args) {
        IdWorker worker2 = new IdWorker(2);
        int i = 0;
        while (i < 20000) {
            worker2.nextId();
        }
    }
}
